import { Repository } from 'typeorm';
import { Task } from './entities/task.entity';
import { InjectRepository } from '@nestjs/typeorm';
import { CreateTasksDto } from './dto/create-tasks.dto';
import { TaskStatus } from './task-status.enum';
import {
  InternalServerErrorException,
  NotFoundException,
} from '@nestjs/common';
import { UpdateTasksStatusDto } from './dto/update-tasks-status.dto';
import { GetTasksFilterDto } from './dto/get-tasks-filter.dto';
import { User } from '../../system/user/entities/user.entity';
import { Logger } from '@nestjs/common';

export class TasksRepository {
  // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  // @ts-ignore
  private logger = new Logger('TasksRepository', true);
  constructor(
    @InjectRepository(Task)
    private repository: Repository<Task>,
  ) {}
  async getTaskList(filterDto: GetTasksFilterDto, user: User): Promise<Task[]> {
    const { status, search } = filterDto;
    const query = this.repository.createQueryBuilder('task');
    if (user.username !== 'admin') {
      query.where({ user });
    }
    if (status) {
      query.andWhere('task.status = :status', { status });
    }
    if (search) {
      query.andWhere(
        '(LOWER(task.title) LIKE LOWER(:search) OR LOWER(task.description) LIKE LOWER(:search))',
        { search: `%${search}%` },
      );
    }
    try {
      query.andWhere('task.isDelete = 0');
      const tasks = await query.getMany();
      return tasks;
    } catch (error) {
      this.logger.error(
        `Faild to get task for user "${
          user.username
        }". Filter: ${JSON.stringify(filterDto)}`,
        error.stack,
      );
      throw new InternalServerErrorException();
    }
  }
  async getTaskById(id: string, user: User): Promise<Task> {
    // eslint-disable-next-line @typescript-eslint/ban-ts-comment
    // @ts-ignore
    // 添加user后将获取当前用户的数据，使用其它用户的任务id将返回404
    const found = await this.repository.findOneBy({ id, isDelete: 0 });
    if (!found) {
      throw new NotFoundException(`参数${id}没有找到！`);
    }
    return found;
  }
  async createTask(createTasksDto: CreateTasksDto, user: User): Promise<Task> {
    const { title, description } = createTasksDto;
    const task = this.repository.create({
      title,
      description,
      status: TaskStatus.OPEN,
      user,
    });
    await this.repository.save(task);
    return task;
  }
  async deleteTask(id: string, user: User): Promise<void> {
    const result = await this.repository.delete({ id, user });
    if (result.affected === 0) {
      throw new NotFoundException(`参数 ${id} 没有找到！`);
    }
  }
  async updateTask(
    updateTasksStatusDto: UpdateTasksStatusDto,
    user: User,
  ): Promise<Task> {
    const { id, status } = updateTasksStatusDto;
    const task = await this.getTaskById(id, user);
    task.status = status;
    await this.repository.save(task);
    return task;
  }
}
